import axios from "axios";
import router from "../router";
import { Message } from 'element-ui';

const instance = axios.create({
    baseURL: '/api/',
    timeout: 50000,
    // 不携带cookie
    withCredentials: false,
    headers: {
      "Content-Type": "application/json"
    }
  });

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
    // 带上token
    if (sessionStorage.getItem('token') !== null) {
        config.headers['Authentication'] = sessionStorage.getItem("token");
    }
    return config;
  }, function (error) {
      Message.error("请求存在问题，请检查")
    return Promise.reject(error);
  });

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    // 处理自定义状态码
    if(response.data.code === 200) {
        return response;
        // 验证码错误放行，以便刷新验证码
    } else if (response.data.code === 1998) {
        return response;
    } else {
      Message.error(response.data.msg);
      return Promise.reject(response.data.msg);
    }

  }, function (error) {
    // 处理http状态码
    if(error.response.data) {
      error.message = error.response.data.msg;
    }
    if(error.response.status === 401) {
      error.message = "登录已过期，请重新登录";
      // 删掉sessionStorage中过期token
      sessionStorage.clear();
      router.push("/");
    }
    if(error.response.status === 403) {
      error.message = "权限不足";
    }
    Message.error(error.message);
    return Promise.reject(error);
  });

export default instance;
